<template>
	<view class="confirm-container">
		<!-- 导航栏 -->
		<nav-bar title="订单确认"></nav-bar>
		
		<!-- 页面内容 -->
		<view class="page-content has-nav-bar">
		
		<!-- 收货地址 -->
		<view class="address-section" @click="navigateToAddress">
			<view v-if="address" class="address-info">
				<view class="address-detail">
					<text class="location-icon">📍</text>
					{{address.province}} {{address.city}} {{address.district}} {{address.detailAddress}}
				</view>
				<view class="user-info">
					<text>{{address.consignee}}</text>
					<text>{{address.phone}}</text>
					<text v-if="address.isDefault" class="default-tag">默认</text>
				</view>
			</view>
			<view v-else class="no-address">
				<text>添加收货地址</text>
			</view>
			<text class="arrow-right">></text>
		</view>
		
		<!-- 商品列表 -->
		<view class="goods-section">
			<view class="goods-header">
				<image src="/static/cart/shop-icon.png" class="shop-icon"></image>
				<text>狗道宠物商城</text>
			</view>
			<view class="cart-list">
				<view class="cart-item" v-for="(item, index) in orderItems" :key="index">
					<image :src="formatImageUrl(item.image)" class="product-image"></image>
					<view class="product-info">
						<text class="product-name">{{item.name}}</text>
						<text class="product-spec">{{item.spec || '默认规格'}}</text>
						<view class="price-quantity">
							<text class="product-price">¥{{item.price}}</text>
							<text class="product-quantity">x{{item.quantity}}</text>
						</view>
					</view>
				</view>
			</view>
		</view>
		
		<!-- 配送方式 -->
		<view class="delivery-section">
			<view class="section-item" @click="chooseDelivery">
				<text>配送方式</text>
				<view class="item-right">
					<text>{{deliveryMethod}}</text>
					<text class="arrow-right">></text>
				</view>
			</view>
		</view>
		
		<!-- 支付方式 -->
		<view class="payment-section">
			<view class="section-item" @click="choosePayment">
				<text>支付方式</text>
				<view class="item-right">
					<text>{{paymentMethod}}</text>
					<text class="arrow-right">></text>
				</view>
			</view>
		</view>
		
		<!-- 优惠券 -->
		<view class="coupon-section">
			<view class="section-item" @click="chooseCoupon">
				<text>优惠券</text>
				<view class="item-right">
					<text v-if="coupon">-¥{{coupon.amount}}</text>
					<text v-else>{{availableCoupons > 0 ? `${availableCoupons}张可用` : '无可用优惠券'}}</text>
					<text class="arrow-right">></text>
				</view>
			</view>
		</view>
		
		<!-- 订单备注 -->
		<view class="remark-section">
			<view class="section-item">
				<text>订单备注</text>
				<input v-model="remark" placeholder="选填，填写订单备注" class="remark-input" />
			</view>
		</view>
		
		<!-- 价格明细 -->
		<view class="price-section">
			<view class="price-item">
				<text>商品金额</text>
				<text>¥{{totalGoodsPrice}}</text>
			</view>
			<view class="price-item">
				<text>运费</text>
				<text>¥{{deliveryFee}}</text>
			</view>
			<view class="price-item" v-if="coupon">
				<text>优惠券</text>
				<text>-¥{{coupon.amount}}</text>
			</view>
			<view class="price-item total">
				<text>实付金额</text>
				<text class="total-price">¥{{actualPrice}}</text>
			</view>
		</view>
		
		<!-- 底部结算栏 -->
		<view class="footer">
			<view class="footer-price">
				<text>实付金额：</text>
				<text class="price">¥{{actualPrice}}</text>
			</view>
			<button class="submit-btn" @click="submitOrder">提交订单</button>
		</view>
		
		<!-- 调试按钮 -->
		<!-- <view class="debug-section" v-if="true">
			<button class="debug-btn" @click="debugAddress">调试地址</button>
		</view> -->
		</view>
	</view>
</template>

<script>
import NavBar from '@/components/NavBar.vue';
import { addressApi } from '@/src/api/address.js';
import { formatImageUrl } from '../../src/utils/imageTools.js';

	export default {
		components: {
			NavBar
		},
		data() {
			return {
				orderItems: [],
				address: null,
				deliveryMethod: '快递配送',
				paymentMethod: '微信支付',
				coupon: null,
				availableCoupons: 2,
				remark: '',
				deliveryFee: 0,
			}
		},
		computed: {
			// 商品总价
			totalGoodsPrice() {
				return this.orderItems.reduce((total, item) => {
					return total + item.price * item.quantity;
				}, 0).toFixed(2);
			},
			// 实际支付金额
			actualPrice() {
				let price = parseFloat(this.totalGoodsPrice) + this.deliveryFee;
				if (this.coupon) {
					price -= this.coupon.amount;
				}
				return price.toFixed(2);
			}
		},
		onLoad(options) {
			// 从缓存中获取订单项
			const orderItems = uni.getStorageSync('orderItems');
			console.log('订单初始化时加载的商品:', orderItems);
			if(orderItems) {
				this.orderItems = orderItems;
			}
		},
		onShow() {
			console.log('页面显示，检查地址状态');
			const selectedAddress = uni.getStorageSync('selectedAddress');
			console.log('缓存中的选择地址:', selectedAddress);
			if (selectedAddress) {
				// 确保地址对象有id字段
				if (!selectedAddress.id) {
					console.error('选择的地址没有ID');
					
					// 尝试查找其他可能的ID字段
					const possibleIdFields = ['_id', 'ID', 'addressId', 'address_id'];
					let foundId = null;
					
					possibleIdFields.forEach(field => {
						if (selectedAddress[field]) {
							console.log(`找到可能的ID字段 ${field}:`, selectedAddress[field]);
							foundId = selectedAddress[field];
						}
					});
					
					if (foundId) {
						console.log('使用替代ID字段:', foundId);
						selectedAddress.id = foundId;
					}
				}
				
				// 确保ID是整数类型
				if (selectedAddress.id && typeof selectedAddress.id === 'string') {
					selectedAddress.id = parseInt(selectedAddress.id);
					console.log('转换后的地址ID:', selectedAddress.id);
				}
				
				this.address = selectedAddress;
				console.log('已设置选择的地址:', this.address);
				uni.removeStorageSync('selectedAddress');
			} else {
				console.log('没有选择的地址，尝试加载默认地址');
				this.loadAddress();
			}
		},
		methods: {
			formatImageUrl,
			debugAddress() {
				console.log('当前地址对象:', this.address);
				if (this.address) {
					console.log('地址ID:', this.address.id);
					console.log('地址ID类型:', typeof this.address.id);
					
					// 尝试重新加载地址
					this.loadAddress();
					
					uni.showModal({
						title: '地址信息',
						content: `ID: ${this.address.id}\n类型: ${typeof this.address.id}\n详情: ${JSON.stringify(this.address)}`,
						showCancel: false
					});
				} else {
					uni.showModal({
						title: '地址信息',
						content: '当前没有选择地址',
						showCancel: false
					});
				}
			},
			loadAddress() {
				console.log('开始加载地址列表');
				addressApi.list().then(res => {
					console.log('地址API返回数据:', JSON.stringify(res));
					if (res.code === 200 && res.data && res.data.length > 0) {
						// 检查每个地址对象的结构
						res.data.forEach((addr, index) => {
							console.log(`地址${index}:`, JSON.stringify(addr));
							console.log(`地址${index} ID:`, addr.id);
							console.log(`地址${index} ID类型:`, typeof addr.id);
							
							// 检查是否有其他可能的ID字段
							const possibleIdFields = ['_id', 'ID', 'addressId', 'address_id'];
							possibleIdFields.forEach(field => {
								if (addr[field]) {
									console.log(`地址${index} 可能的ID字段 ${field}:`, addr[field]);
								}
							});
						});
						
						let defaultAddress = res.data.find(addr => !!addr.is_default || !!addr.isDefault);
						let selectedAddr = defaultAddress || res.data[0];
						
						// 确保地址对象有id字段
						if (!selectedAddr.id) {
							console.error('选择的地址没有ID字段');
							
							// 尝试查找其他可能的ID字段
							const possibleIdFields = ['_id', 'ID', 'addressId', 'address_id'];
							let foundId = null;
							
							possibleIdFields.forEach(field => {
								if (selectedAddr[field]) {
									console.log(`找到可能的ID字段 ${field}:`, selectedAddr[field]);
									foundId = selectedAddr[field];
								}
							});
							
							if (foundId) {
								console.log('使用替代ID字段:', foundId);
								selectedAddr.id = foundId;
							}
						}
						
						// 确保地址ID是整数
						if (selectedAddr.id && typeof selectedAddr.id === 'string') {
							selectedAddr.id = parseInt(selectedAddr.id);
						}
						
						this.address = selectedAddr;
						console.log('已加载地址:', JSON.stringify(this.address));
						console.log('地址ID类型:', typeof this.address.id);
					} else {
						console.log('没有可用地址');
						this.address = null;
					}
				}).catch(err => {
					console.error('获取地址失败:', err);
					this.address = null;
				});
			},
			navigateToAddress() {
				uni.navigateTo({
					url: '/pages/address/index?from=confirm'
				});
			},
			chooseDelivery() {
				// TODO: 实现配送方式选择
				uni.showToast({ title: '功能开发中', icon: 'none' });
			},
			choosePayment() {
				uni.showActionSheet({
					itemList: ['微信支付', '支付宝支付', '余额支付'],
					success: (res) => {
						const methods = ['微信支付', '支付宝支付', '余额支付'];
						this.paymentMethod = methods[res.tapIndex];
					}
				});
			},
			chooseCoupon() {
				if (this.availableCoupons <= 0) {
					uni.showToast({
						title: '暂无可用优惠券',
						icon: 'none'
					});
					return;
				}
				
				uni.navigateTo({
					url: '/pages/coupon/list?from=order'
				});
				
				// 模拟选择优惠券
				setTimeout(() => {
					this.coupon = {
						id: 1,
						name: '满100减10',
						amount: 10
					};
				}, 2000);
			},
			submitOrder() {
				console.log('开始提交订单，当前地址对象:', this.address);
				if (!this.address) {
					uni.showToast({
						title: '请选择收货地址',
						icon: 'none'
					});
					return;
				}
				
				// 添加调试信息
				console.log('提交订单的地址信息:', JSON.stringify(this.address));
				console.log('地址ID类型:', typeof this.address.id);
				console.log('地址ID值:', this.address.id);
				
				// 确保地址对象有id字段
				if (!this.address.id) {
					console.error('地址对象没有ID字段');
					
					// 尝试查找其他可能的ID字段
					const possibleIdFields = ['_id', 'ID', 'addressId', 'address_id'];
					let foundId = null;
					
					possibleIdFields.forEach(field => {
						if (this.address[field]) {
							console.log(`找到可能的ID字段 ${field}:`, this.address[field]);
							foundId = this.address[field];
						}
					});
					
					if (foundId) {
						console.log('使用替代ID字段:', foundId);
						this.address.id = foundId;
					} else {
						uni.showToast({
							title: '地址信息不完整，请重新选择地址',
							icon: 'none'
						});
						return;
					}
				}
				
				// 确保addressId是整数类型
				let addressId = null;
				try {
					if (this.address.id) {
						addressId = parseInt(this.address.id);
						console.log('解析后的地址ID:', addressId);
						
						if (isNaN(addressId)) {
							console.error('地址ID无法转换为整数');
							uni.showToast({
								title: '地址信息错误，请重新选择地址',
								icon: 'none'
							});
							return;
						}
					} else {
						console.error('地址ID为空或无效');
						uni.showToast({
							title: '地址信息不完整，请重新选择地址',
							icon: 'none'
						});
						return;
					}
				} catch (e) {
					console.error('解析地址ID出错:', e);
					uni.showToast({
						title: '地址信息错误，请重新选择地址',
						icon: 'none'
					});
					return;
				}
				
				const orderDTO = {
					// addressId: addressId, // 不再使用
					address: {
						consignee: this.address.consignee,
						phone: this.address.phone,
						province: this.address.province,
						city: this.address.city,
						district: this.address.district,
						detailAddress: this.address.detailAddress
					},
					payType: this.paymentMethod === '微信支付' ? 1 : (this.paymentMethod === '支付宝支付' ? 2 : 3), // 1:微信, 2:支付宝, 3:余额
					remark: this.remark,
					items: this.orderItems.map(item => ({
						productId: item.product_id,
						quantity: item.quantity,
						spec: item.spec
					}))
				};
				
				// 打印完整的订单DTO
				console.log('提交的订单数据:', JSON.stringify(orderDTO));
				
				// 调用创建订单API
				this.$api.orderApi.create(orderDTO).then(res => {
					console.log('订单创建API返回:', res);
					if (res.code === 200) {
						// 清除缓存中的订单项
						uni.removeStorageSync('orderItems');
						
						// 跳转到支付成功页面或支付页面
						uni.redirectTo({
							url: `/pages/order/success?orderId=${res.data.orderId}`
						});
					} else {
						uni.showToast({ title: res.msg || '订单创建失败', icon: 'none' });
					}
				}).catch(err => {
					console.error('订单创建失败:', err);
					uni.showToast({ title: '订单创建失败，请稍后再试', icon: 'none' });
				})
			}
		}
	}
</script>

<style lang="scss">
	.confirm-container {
		background-color: #f7f7f7;
		min-height: 100vh;
	}
	
	.page-content {
		padding-bottom: 120rpx; /* 为底部结算栏留出空间 */
	}
	
	.has-nav-bar {
		padding-top: 90rpx; /* 假设自定义导航栏高度为 90rpx */
	}
	
	/* 收货地址 */
	.address-section {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 30rpx;
		background-color: #fff;
		margin: 20rpx;
		border-radius: 16rpx;
		box-shadow: 0 4rpx 20rpx rgba(0,0,0,0.05);
	}
	
	.address-info {
		flex: 1;
	}
	
	.address-detail {
		font-size: 28rpx;
		font-weight: bold;
		margin-bottom: 10rpx;
		display: flex;
		align-items: center;
	}
	
	.location-icon {
		margin-right: 10rpx;
		font-size: 32rpx;
		color: #FF7043;
	}
	
	.user-info {
		font-size: 26rpx;
		color: #666;
		padding-left: 42rpx;
		
		text {
			margin-right: 20rpx;
		}
	}
	
	.default-tag {
		background-color: #fa3534;
		color: #fff;
		padding: 2rpx 10rpx;
		border-radius: 6rpx;
		font-size: 20rpx;
		margin-left: 10rpx;
	}
	
	.no-address {
		flex: 1;
		color: #666;
		font-size: 28rpx;
	}

	.arrow-right {
		color: #999;
		font-size: 32rpx;
	}

	/* 商品列表 */
	.goods-section {
		background-color: #fff;
		margin-bottom: 20rpx;
		
		.goods-header {
			display: flex;
			align-items: center;
			padding: 30rpx;
			border-bottom: 1rpx solid #f5f5f5;
			
			.shop-icon {
				width: 40rpx;
				height: 40rpx;
				margin-right: 20rpx;
			}
			
			text {
				font-size: 30rpx;
				font-weight: bold;
			}
		}
		
		.cart-list {
			.cart-item {
				display: flex;
				padding: 30rpx;
				border-bottom: 1rpx solid #f5f5f5;
				align-items: center;

				&:last-child {
					border-bottom: none;
				}
				
				.product-image {
					width: 160rpx;
					height: 160rpx;
					border-radius: 10rpx;
					margin-right: 20rpx;
				}
				
				.product-info {
					flex: 1;
					display: flex;
					flex-direction: column;
					justify-content: space-between;
					
					.product-name {
						font-size: 28rpx;
						color: #333;
						margin-bottom: 10rpx;
						display: -webkit-box;
						-webkit-box-orient: vertical;
						-webkit-line-clamp: 2;
						line-clamp: 2;
						overflow: hidden;
					}
					
					.product-spec {
						font-size: 24rpx;
						color: #999;
						margin-bottom: 20rpx;
					}
					
					.price-quantity {
						display: flex;
						justify-content: space-between;
						align-items: center;
						
						.product-price {
							font-size: 30rpx;
							color: #FF6600;
							font-weight: bold;
						}
						
						.product-quantity {
							font-size: 28rpx;
							color: #999;
						}
					}
				}
			}
		}
	}
	
	.delivery-section,
	.payment-section,
	.coupon-section,
	.remark-section {
		background-color: #fff;
		margin-bottom: 20rpx;
		
		.section-item {
			display: flex;
			align-items: center;
			justify-content: space-between;
			padding: 30rpx;
			
			text {
				font-size: 28rpx;
				color: #333;
			}
			
			.item-right {
				display: flex;
				align-items: center;
				
				text {
					margin-right: 10rpx;
					color: #666;
				}
				
				.arrow-right {
					font-size: 32rpx;
					color: #999;
				}
			}
			
			.remark-input {
				flex: 1;
				text-align: right;
				font-size: 28rpx;
				color: #666;
			}
		}
	}
	
	.price-section {
		background-color: #fff;
		margin-bottom: 20rpx;
		padding: 30rpx;
		
		.price-item {
			display: flex;
			justify-content: space-between;
			margin-bottom: 20rpx;
			
			text {
				font-size: 28rpx;
				color: #666;
			}
			
			&.total {
				margin-top: 30rpx;
				padding-top: 20rpx;
				border-top: 1rpx solid #f5f5f5;
				
				text {
					font-size: 30rpx;
					color: #333;
					font-weight: bold;
					
					&.total-price {
						color: #FF6600;
						font-size: 36rpx;
					}
				}
			}
		}
	}
	
	.footer {
		position: fixed;
		left: 0;
		right: 0;
		bottom: 0;
		height: 100rpx;
		background-color: #fff;
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 0 30rpx;
		box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
		
		.footer-price {
			display: flex;
			align-items: center;
			
			text {
				font-size: 28rpx;
				color: #333;
				
				&.price {
					color: #FF6600;
					font-size: 36rpx;
					font-weight: bold;
				}
			}
		}
		
		.submit-btn {
			width: 240rpx;
			height: 80rpx;
			line-height: 80rpx;
			background-color: #FF6600;
			color: #fff;
			font-size: 30rpx;
			font-weight: bold;
			border-radius: 40rpx;
		}
	}

	/* 调试样式 */
	.debug-section {
		padding: 20rpx;
		display: flex;
		justify-content: center;
		margin-top: 20rpx;
	}

	.debug-btn {
		background-color: #007AFF;
		color: #fff;
		font-size: 24rpx;
		padding: 10rpx 20rpx;
		border-radius: 10rpx;
	}
</style> 